package com.example.servlet;

import com.example.model.Article;
import com.example.util.DBUtil;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class HomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Article> articles = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM articles ORDER BY views DESC, create_time DESC")) {
            while (rs.next()) {
                Article article = new Article();
                article.setId(rs.getInt("id"));
                article.setTitle(rs.getString("title"));
                article.setType(rs.getString("type"));
                article.setContent(rs.getString("content"));
                article.setAuthor(rs.getString("author"));
                article.setCreateTime(rs.getTimestamp("create_time"));
                article.setViews(rs.getInt("views"));
                article.setLikes(rs.getInt("likes"));
                articles.add(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        req.setAttribute("articles", articles);
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }
} 